package cn.bisoft.java.test;

import java.io.File;
import java.util.List;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
import com.thoughtworks.xstream.converters.reflection.Sun14ReflectionProvider;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.XppDriver;
import com.thoughtworks.xstream.persistence.FilePersistenceStrategy;
import com.thoughtworks.xstream.persistence.PersistenceStrategy;
import com.thoughtworks.xstream.persistence.XmlArrayList;

/**
 * XStreamFacade
 * 
 * <pre>
 * 提供对XStream的初始化,降低使用XStream API的复杂性.
 * @link 
 * </pre>
 * @author tl
 * @version 1.0, 2011-6-10
 */
public class XStreamFacade
{
	public static final String JAXP_DOM_XML_PARSER = "JAXP DOM";

	public static final String XPP3_XML_PARSER = "XPP3";

	public static final String STAX_JSON_PARSER = "Jettison StAX";

	public static final String WRITER_JSON_PARSER = "JSON Writer";

	/**
	 * 获取XStream对象.
	 * 
	 * <pre>
	 * 根据驱动获取XStream对象,若没有提供驱动,则默认使用JAXP-DOM驱动.
	 * </pre>
	 * @param driver 驱动名称
	 * @param isStaticSupported 是否支持静态变量转换
	 * @return XStream
	 */
	public synchronized static XStream getXStream(String driver, boolean isStaticSupported)
	{
		ReflectionProvider reflectProvider = null;

		if (isStaticSupported)
		{
			reflectProvider = new EnhancedModeReflectProvider();
		}
		else
		{
			reflectProvider = new Sun14ReflectionProvider();
		}

		if (JAXP_DOM_XML_PARSER.equals(driver))
		{

			xstream = new XStream(reflectProvider, new DomDriver());
			xstream.autodetectAnnotations(true);

			System.err.println(xstream.getReflectionProvider());
		}
		else if (XPP3_XML_PARSER.equals(driver))
		{
			xstream = new XStream(reflectProvider, new XppDriver());
			xstream.autodetectAnnotations(true);
		}
		else if (STAX_JSON_PARSER.equals(driver))
		{
			xstream = new XStream(reflectProvider, new JettisonMappedXmlDriver());
			xstream.setMode(XStream.NO_REFERENCES);
		}
		else if (WRITER_JSON_PARSER.equals(driver))
		{
			xstream = new XStream(reflectProvider, new JsonHierarchicalStreamDriver());
			xstream.setMode(XStream.NO_REFERENCES);
		}
		else
		{
			xstream = new XStream(reflectProvider, new DomDriver());
		}

		return xstream;
	}

	/**
	 * 持久化对象列表.
	 * 
	 * <pre>
	 * 		持久化对象列表,存储到指定用户主目录下的指定目录
	 * </pre>
	 * @param dir 目录
	 * @param objects 对象列表
	 */
	@SuppressWarnings("unchecked")
	public void persist(String dir, List objects)
	{
		PersistenceStrategy strategy = new FilePersistenceStrategy(new File(System.getProperty("user.home"), dir));

		List<?> list = new XmlArrayList(strategy);

		list.addAll(objects);
	}

	private static XStream xstream;

}
